'use strict';

const Controller = require('egg').Controller;
const SELECT = require('../../../../config/select');
const routerAndRole = async (ctx,destory = false) => {
    const body = ctx.request.body;
    const routerId = body.routerId;
    const roleId = body.roleId;
    const Rules = {
        routerId: {
            type: 'objectId',
            keyname: '路由ID'
        },
        roleId: {
            type: 'objectId',
            keyname: '角色ID'
        }
    };
    ctx.proving(Rules);
    
    await ctx.service.router.routerAndRole(routerId, roleId, destory);
    ctx.success({
        message: destory ? '角色移除成功' : '角色授予成功'
    })
}

class RouterController extends Controller {
    /**
     * 获取路由
     */
    async find() {
        const {ctx} = this;
        const {id, name, page, currentPage} = ctx.query;
        const select = SELECT.ROUTER;
        const Rules = {
            id: {
                type: 'objectId',
                required : false
            }
        };
        ctx.proving(Rules, ctx.query);
        const router = await ctx.service.router.find({id, name, page, currentPage},select);
        ctx.success(router);
    }
    /*
    * 为路由添加角色
    * */
    async addRole(destory = false) {
        const {ctx} = this;
        // 角色权限认证
        await ctx.powerValidate();
        await routerAndRole(ctx);
    }

    /*
    * 为路由移除角色
    * */
    async destroyRole() {
        const {ctx} = this;
        // 角色权限认证
        await ctx.powerValidate();
        await routerAndRole(ctx,true);
    }
}

module.exports = RouterController;
